

package com.hazelcast.internal.serialization.impl.compact;

import com.hazelcast.nio.serialization.FieldKind;
import com.hazelcast.nio.serialization.HazelcastSerializationException;
import com.hazelcast.nio.serialization.genericrecord.GenericRecord;
import com.hazelcast.nio.serialization.genericrecord.GenericRecordBuilder;

import javax.annotation.Nonnull;
import java.util.TreeMap;

/**
 * This builder is build by user thread via
 * {@link GenericRecordBuilder#compact(String)} method.
 * <p>
 * It is only job to carry the objects including their types and the class name.
 */
public class DeserializedGenericRecordBuilder extends AbstractGenericRecordBuilder {

    private final TreeMap<String, Object> objects;
    private final SchemaWriter schemaWriter;
    private boolean built;

    public DeserializedGenericRecordBuilder(String typeName) {
        this.objects = new TreeMap<>();
        schemaWriter = new SchemaWriter(typeName);
    }

    /**
     * @return newly created GenericRecord
     */
    @Nonnull
    @Override
    public GenericRecord build() {
        this.built = true;
        return new DeserializedGenericRecord(schemaWriter.build(), objects);
    }


    @Override
    protected GenericRecordBuilder write(@Nonnull String fieldName, Object value, FieldKind fieldKind) {
        if (this.built) {
            throw new UnsupportedOperationException("Cannot modify the GenericRecordBuilder after building");
        }
        if (objects.putIfAbsent(fieldName, value) != null) {
            throw new HazelcastSerializationException("Field can only be written once");
        }
        schemaWriter.addField(new FieldDescriptor(fieldName, fieldKind));
        return this;
    }

}
